package photo_upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileService {
	public void makeBasePath(String path) {
        File dir = new File(path);
        if (!dir.exists()) dir.mkdirs();
	} 
	
    public String saveFile(File file, String basePath, String fileName) throws IOException {
		if (null == file || file.getName().equals("") || file.length() <= 0) return null;
		
		//make folder for base path
        makeBasePath(basePath);
        
        //make server full path to save
        String serverFullPath = basePath + "\\" + fileName;

        //write file
        FileInputStream inputStream = new FileInputStream(file);
        FileOutputStream outputStream = new FileOutputStream(serverFullPath);
        int bytesRead = 0;
        byte[] buffer = new byte[1024];
        while ((bytesRead = inputStream.read(buffer, 0, 1024)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.close();
        inputStream.close();
        
        return serverFullPath;
	}
}
